//
//  XMWebViewManager.m
//  XMUI_OC
//
//  Created by zhangmingwei6 on 2023/5/19.
// NSURLRequestUseProtocolCachePolicy：默认策略，具体的缓存逻辑和协议的声明有关，如果协议没有声明，不需要每次重新验证cache。    如果请求协议头为no-cache，则表现为直接从后台请求数据


#import "XMWebViewManager.h"
#import "XMSizeMacro.h"
#import <WebKit/WebKit.h>

@interface XMWebViewManager()<WKNavigationDelegate, WKUIDelegate>

/// 预加载的网页
@property (nonatomic, strong) NSMutableArray    *preloadWebViewArray;

@end

@implementation XMWebViewManager

+ (instancetype)defalutManager {
    static XMWebViewManager *webviewManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        webviewManager = [[XMWebViewManager alloc] init];
        webviewManager.preloadWebViewArray = [NSMutableArray array];
        webviewManager.urlArr = [NSMutableArray array];
        webviewManager.maxCacheCount = 20;
    });
    return webviewManager;
}

/// 根据url获取webview
- (WKWebView *)getWebView:(NSString *)urlString {
    WKWebView *webV = nil;
    for (NSDictionary *dict in self.preloadWebViewArray) {
        if ([dict[@"url"] isEqualToString:urlString]) {
            webV = dict[@"webview"];
        }
    }
    if (webV == nil) {
        webV = [self preloadWebViewWithUrlString:urlString];
    }
    return webV;
}

/// 预加载网页
- (WKWebView *)preloadWebViewWithUrlString:(NSString *)urlString {
    if (!urlString || urlString.length <= 0) {
        return nil;
    }
    WKWebViewConfiguration *configuretion = [[WKWebViewConfiguration alloc] init];
    configuretion.preferences = [[WKPreferences alloc]init];
    configuretion.preferences.minimumFontSize = 3;
    configuretion.preferences.javaScriptEnabled = YES;
    configuretion.processPool = [[WKProcessPool alloc]init];
    //默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
    configuretion.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    WKWebView *webV = [[WKWebView alloc] initWithFrame:CGRectMake(0, kNaviStatusBarH_XM, kScreenWidth_XM, kScreenHeight_XM - kNaviStatusBarH_XM) configuration:configuretion];
    webV.UIDelegate = self;
    webV.navigationDelegate = self;
    webV.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    webV.backgroundColor = [UIColor whiteColor];
    webV.allowsBackForwardNavigationGestures = YES;
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [webV loadRequest:req];
    [webV reload];
    NSMutableDictionary *urlWebViewDict = [NSMutableDictionary dictionary];
    [urlWebViewDict setValue:webV forKey:@"webview"];
    [urlWebViewDict setValue:urlString forKey:@"url"];
    [self addPreloadAction:urlWebViewDict];
    return webV;
}

/// 批量预加载网页方法
- (void)preloadWebViewWithUrlArray:(NSArray *)urlArray {
    for (NSString *urlString in urlArray) {
        [self preloadWebViewWithUrlString:urlString];
    }
}

/// 添加到预加载数组中
- (void)addPreloadAction:(NSDictionary *)dict {
    BOOL isExistFlag = NO;
    for (int i = 0; i < self.preloadWebViewArray.count; i++) {
        NSDictionary *urlwebDict = self.preloadWebViewArray[i];
        if ([urlwebDict[@"url"] isEqualToString:dict[@"url"]]) {
            isExistFlag = YES;
            [self.preloadWebViewArray replaceObjectAtIndex:i withObject:dict];
        }
    }
    if (!isExistFlag) {
        // 最多添加几个缓存的webview
        if (self.preloadWebViewArray.count < self.maxCacheCount) {
            [self.preloadWebViewArray addObject:dict];
        } else {
            [self.preloadWebViewArray replaceObjectAtIndex:0 withObject:dict];
        }
    }
}

/// 清除上个页面的缓存 - 防止展示上个网页的内容
//- (void)clearAction:(WKWebView *)webV {
//    [webV evaluateJavaScript:@"window.document.body.remove();" completionHandler:^(id _Nullable, NSError * _Nullable error) {
//
//    }];
//}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // NSURLRequestReturnCacheDataElseLoad 优先从本地拿数据，但是如果没有本地cache，则请求源数据
}

#pragma mark - 封装刷新更新本地url数组的方法
+ (void)reloadLocalUrlArrayAction {
    // 预加载多个网页
    NSMutableArray *urlArray = [NSMutableArray array];
    NSArray *localArr = [[NSUserDefaults standardUserDefaults] objectForKey:@"kUrlArr"];
    if (localArr.count <= 0) {
        [urlArray addObject:@"https://s.weibo.com/top/summary?cate=realtimehot"];
        [urlArray addObject:@"http://top.baidu.com/m/#buzz/1"];
        [urlArray addObject:@"https://m.36kr.com/hot-list-m"];
        [urlArray addObject:@"https://m.yicai.com/news/"];
        [urlArray addObject:@"https://wallstreetcn.com/news/global"];
        [urlArray addObject:@"https://m.baidu.com"];
        [urlArray addObject:@"https://tonzhon.com"];
        [urlArray addObject:@"http://m.jrskk.com/"];
        [[NSUserDefaults standardUserDefaults] setObject:urlArray forKey:@"kUrlArr"];
    } else {
        urlArray = [NSMutableArray arrayWithArray:localArr];
    }

    [XMWebViewManager defalutManager].urlArr = urlArray;
    [[XMWebViewManager defalutManager] preloadWebViewWithUrlArray:[XMWebViewManager defalutManager].urlArr];

///// 具体页面的使用方式：
//    WKWebView *webV = [[XMWebViewManager defalutManager] getWebView:@"https://www.baidu.com"];
//    [self.view addSubview:webV];
//    [webV reload]; // reload能保证刷新最新的状态
}

@end


